#pragma once
#include <iostream>
#include <string>
#include <sys/epoll.h>
#include "Log.hpp"
#include <cstring>
#include <cerrno>
using namespace std;


namespace EpollerModule {
    const int defaultepfd = -1;
    const int defaultsize = 128;
    class Epoller {
    public :
        Epoller() 
            :_epfd(defaultepfd)
        {

        }
        // 初始化epoll
        void InitEpoller() {
            _epfd = epoll_create(defaultsize);
            if (_epfd < 0) {
                lg.LogMessage(Fatal, "create epoll error errorno: %d, errorstring: %s", errno, strerror(errno));
                exit(-1);
            }
            lg.LogMessage(Info, "create epoll success! epollfd: %d", _epfd);
        }

        // 向epoll模型中添加事件
        void AddEvent(int sockfd, uint32_t events) {
            struct epoll_event ev;
            ev.events = events;
            ev.data.fd = sockfd; // 这是给用户用的
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        }

        // 从epoll中删除事件
        void DelEvent(int sockfd) {
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
        }

        // epoll的等待
        int Wait(struct epoll_event* revs, int maxevents, int timeout) {
            int n = epoll_wait(_epfd, revs, maxevents, timeout);
            return n;
        }

        ~Epoller() {

        }

    private :
        int _epfd;
    };
    
};
